<template>
  <div class="register flex-center wh-full relative overflow-scroll">
    <!-- 注册页头部 -->
    <div class="flex-x-end absolute top-0 w-full p-4">
      <el-switch
        v-model="isDark"
        inline-prompt
        active-icon="Moon"
        inactive-icon="Sunny"
        @change="toggleTheme"
      />
      <lang-select class="ml-2 cursor-pointer" />
    </div>

    <!-- 注册页内容 -->
    <div
      class="m-5 w-full min-w-[335px] max-w-[460px] p-5 shadow-[var(--el-box-shadow-light)] sm:p-10"
      :class="[isDark ? 'bg-transparent' : 'bg-white']"
    >
      <div class="flex-center relative pb-5">
        <h2 class="text-2xl font-bold">{{ t("register.title") }}</h2>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerFormData"
        :rules="rules"
        @submit.prevent="handleRegister"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerFormData.username"
            :placeholder="t('register.username')"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerFormData.mobile"
            :placeholder="t('register.mobile')"
            prefix-icon="Phone"
          />
        </el-form-item>

        <el-form-item prop="areaCode">
          <el-popover
            ref="areaPopoverRef"
            placement="bottom-start"
            :width="380"
            trigger="click"
            popper-class="custom-tree-select-popover"
          >
            <template #reference>
              <el-input
                v-model="selectedAreaName"
                placeholder="选择行政区划"
                readonly
                @click="() => {}"
                clearable
                @clear="clearAreaSelection"
              >
                <template #prefix>
                  <el-icon><Location /></el-icon>
                </template>
              </el-input>
            </template>
            <div class="tree-container">
              <el-tree
                ref="areaTreeRef"
                :data="regionOptions"
                node-key="areaCode"
                :props="{
                  isLeaf: (data) => data.level === 5,
                  label: 'name',
                  children: 'children',
                  level: 'level',
                }"
                :load="loadRegionNodes"
                lazy
                @node-click="handleAreaNodeClick"
              />
            </div>
          </el-popover>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerFormData.password"
            type="password"
            show-password
            :placeholder="t('register.password')"
            prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerFormData.confirmPassword"
            type="password"
            show-password
            :placeholder="t('register.confirmPassword')"
            prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item prop="recommenderId">
          <el-input
            v-model="registerFormData.recommenderId"
            :placeholder="t('register.recommenderId')"
            prefix-icon="Promotion"
          />
        </el-form-item>

        <el-button type="primary" class="w-full" :loading="loading" native-type="submit">
          {{ t("register.submit") }}
        </el-button>

        <div class="mt-4 text-center">
          <el-link type="info" @click="$router.push('/login')">
            {{ t("register.haveAccount") }}
          </el-link>
        </div>
      </el-form>
    </div>

    <!-- 注册页底部 -->
    <el-text size="small" class="py-2.5! fixed bottom-0 text-center">
      Copyright © 2021 - 2025 youlai.tech All Rights Reserved.
      <a href="http://beian.miit.gov.cn/" target="_blank">皖ICP备20006496号-2</a>
    </el-text>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import AuthAPI from "@/api/auth.api";
import RegionAPI from "@/api/system/region.api.js";
import { ThemeMode } from "@/enums/settings/theme.enum";
import { useSettingsStore } from "@/store";

const { t } = useI18n();
const router = useRouter();
const registerFormRef = ref(null);

const settingsStore = useSettingsStore();
const isDark = ref(settingsStore.theme === ThemeMode.DARK);

const registerFormData = ref({
  username: "",
  mobile: "",
  password: "",
  confirmPassword: "",
  recommenderId: "",
  areaCode: "",
});

const rules = {
  username: [
    { required: true, message: t("register.usernameRequired"), trigger: "blur" },
    { min: 3, max: 16, message: t("register.usernameLength"), trigger: "blur" },
  ],
  phone: [
    { required: true, message: t("register.mobileRequired"), trigger: "blur" },
    { type: "phone", message: t("register.mobileFormat"), trigger: "blur" },
  ],
  password: [
    { required: true, message: t("register.passwordRequired"), trigger: "blur" },
    { min: 6, message: t("register.passwordMinLength"), trigger: "blur" },
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (value !== registerFormData.value.password) {
          callback(new Error(t("register.passwordNotMatch")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  areaCode: [
    { required: true, message: "请选择行政区划", trigger: "change" },
  ],
};

const loading = ref(false);
let redirectTimer = null;

// 区域选择相关
const regionOptions = ref([]);
const areaPopoverRef = ref(null);
const areaTreeRef = ref(null);
const selectedAreaName = ref("");
const treeNodeMap = ref(new Map());

// 懒加载行政区划节点
function loadRegionNodes(node, resolve) {
  if (node.level === 0) {
    // 根节点，加载省级数据
    RegionAPI.getOptions({ type: 0, areaCode: 0 })
      .then((data) => {
        regionOptions.value = data;
        data.forEach((item) => {
          treeNodeMap.value.set(item.areaCode, item);
        });
        resolve(data);
      })
      .catch(() => {
        resolve([]);
      });
    return;
  }
  
  // 根据当前节点级别确定请求的type值
  const type = node.level;
  // 使用当前节点的areaCode作为请求参数
  const areaCode = node.data.areaCode;
  
  RegionAPI.getOptions({ type, areaCode })
    .then(data => {
      data.forEach(item => {
        treeNodeMap.value.set(item.areaCode, item);
      });
      resolve(data);
    })
    .catch(() => {
      resolve([]);
    });
}

function handleAreaNodeClick(data, node) {
  if (data.level === 5) {
    registerFormData.value.areaCode = data.areaCode;
    let currentNode = node;
    let pathNames = [];
    while (currentNode && currentNode.level > 0) {
      pathNames.unshift(currentNode.label);
      currentNode = currentNode.parent;
    }
    selectedAreaName.value = pathNames.join(" - ");
    areaPopoverRef.value.hide();
  }
}

function clearAreaSelection() {
  registerFormData.value.areaCode = null;
  selectedAreaName.value = "";
}

const handleRegister = async () => {
  try {
    const isValid = await registerFormRef.value?.validate();
    if (!isValid) return;

    loading.value = true;
    await AuthAPI.doRegister(registerFormData.value).then((data) => {
      if (data) {
        ElMessage.success(t("register.success"));
        redirectTimer = setTimeout(() => {
          router.push("/login");
        }, 1500);
      } else {
        ElMessage.error(t("register.failure"));
      }
    });
  } catch (error) {
    console.error("登录失败:", error);
  } finally {
    loading.value = false;
  }
};

onBeforeUnmount(() => {
  if (redirectTimer) clearTimeout(redirectTimer);
});

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeMode.DARK ? ThemeMode.LIGHT : ThemeMode.DARK;
  settingsStore.changeTheme(newTheme);
};
</script>

<style lang="scss" scoped>
.register {
  background: url("@/assets/images/login-bg.jpg") no-repeat center right;
}

html.dark {
  .register {
    background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
    .el-card {
      background: transparent;
    }
  }
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-input) {
  height: 48px;
  .el-input__wrapper {
    padding: 1px 10px;
  }
}

.tree-container {
  max-height: 300px;
  overflow-y: auto;
  border-radius: 0.5rem;
  background-color: white;
}
</style>
